from pymysql.converters import escape_string

from configs import logger
from datetime import datetime
from hetong.db.lib_job.session import with_session
from sqlalchemy import text


@with_session
def get_tasks(session, type=11, status=0):
    '''
    type  11 为合同 staus=0 为未开始
    '''
    sql = f'''select * from f_library_job  where type ={type}  and status = {status}'''
    fetch = session.execute(text(sql))
    result = fetch.fetchall()
    data = [row._asdict() for row in result]
    return data


@with_session
def update_percentage(session, id):
    try:
        sql = f'''select * from f_library_job  where id ={id} '''
        fetch = session.execute(text(sql))
        result = fetch.fetchall()
        data = [row._asdict() for row in result]
        if data:
            one = data[0]
            percentage = one['percentage']
            cur_percentage = percentage + 1
            if cur_percentage >= 100:
                cur_percentage = 98
            update_percentage(id, percentage=cur_percentage)
    except Exception as e:
        logger.error(e)


@with_session
def update_task(session, id, status=None, remote_path=None, end_time=None, percentage=None, reasons=None,
                start_time=None):
    sql_results = []
    if status:
        sql_status = f'''status = {status}'''
        sql_results.append(sql_status)
    if remote_path:
        sql_remote_path = f''' source_file = '{remote_path}' '''
        sql_results.append(sql_remote_path)
    if percentage:
        sql_percentage = f'''percentage = {percentage}'''
        sql_results.append(sql_percentage)
    if end_time:
        end_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        sql_end_time = f'''end_time = '{end_time}' '''
        sql_results.append(sql_end_time)
    if start_time:
        start_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        sql_start_time = f'''start_time = '{start_time}' '''
        sql_results.append(sql_start_time)
    if reasons:
        sql_reasons = f'''reasons = '{escape_string(reasons)}' '''
        sql_results.append(sql_reasons)
    if len(sql_results) == 0:
        return
    update_sql = f''' update f_library_job set {','.join(sql_results)}  where id = {id}'''
    session.execute(text(update_sql))

if __name__ == '__main__':
    update_task(id=1257,reasons="'wefewf")